<script lang="ts" setup>
import { ref, reactive, watch, type VNode, h } from 'vue'
import {
  NSpace,
  NButton,
  type FormInst,
  NForm,
  NFormItem,
  NSelect,
  type FormRules,
  useMessage,
  NScrollbar,
  NSpin,
  NEllipsis,
  type SelectOption,
  NTooltip,
  NTimeline,
  NTimelineItem
} from 'naive-ui'
// import VUpload from '@/views/OA/Common/Upload.vue'
import { sendRequest } from '@/utils/api'
import FixedAction from '@/components/FixedAction.vue'
import { keysOf } from '@/utils/object'
import { useRoute } from 'vue-router'
import VAttachments from '@/views/OA/Common/Attachments.vue'
import useSubmit, {
  defaultVersionTypeValue,
  defaultVersionTypeKey
} from '@/components/DynamicFormComponent/useSubmit'
import DynamicFormComponent from '@/components/DynamicFormComponent/index.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
import BatchInfo from '@/views/Collection/Collect/Batch/components/BatchInfo.vue'
import FUploader from '@/views/Collection/Collect/Batch/components/FUploader.vue'

const { dfInst, formData, createVars, submitLoading, submit: submitR } = useSubmit()
// const props = defineProps({
//   id: { type: String, default: () => null },
//   type: { type: Number, default: () => 0 },
// })
const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const array = route.query.id || []
const message = useMessage()
const userFormRef = ref<FormInst | null>(null)
const loading = ref(false)
const form: any = reactive({
  id: array?.[0],
  password: array?.[0] ? null : 'Aa123456!',
  userStatus: 1,
  typeTree: null,
  typeTreeS: null,
  typeTreeT: null,
  time: null,
  name: null,
  repactName: null,
  collectName: null,
  phone: null,
  person: null,
  dujiaoName: null,
  Uptime: null,
  price: null,
  author: null,
  number1: null,
  yesNO: null,
  yinciTime: null,
  remack: null,
  ziicaCode: null,
  serialNumber: null,
  position: null,
  itemsStaging: {
    firstLevelCode: null,
    threeLevelCode: null,
    secondLevelCode: null,
    fifthLevelCode: null,
    fourthLevelCode: null,
    serialNumber: null,
    subItemCode: null
  }
})
const renderOption1 = ref(({ node, option }: { node: VNode; option: SelectOption }) =>
  h(NTooltip, null, {
    trigger: () => node,
    default: () => option.label
  })
)
const fileImgList: any = ref([]) //附件数组
const optionInPosition0 = ref([])
const optionInPosition1 = ref([])
const optionInPosition2 = ref([])
const optionInPosition3 = ref([])
const optionInPosition4 = ref([])
const optionInPosition5 = ref([])
const formRules: FormRules = {
  itemsStaging: {
    firstLevelCode: {
      // required: optionInPosition0.value.length > 0 ? true : false,
      required: true,
      trigger: ['blur', 'change'],
      type: 'any',
      message: '不能为空'
    }
  }
}

const getFirstFn = async (id: any, refValue: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listOptionsByParentId',
    override: {
      params: {
        parentId: id
      }
    }
  })
  if (error) return message.error(error.message)
  refValue.value = res?.data || []
}

const changeOptionFn = (e: any, type: any) => {
  switch (type) {
    case 1: {
      form.itemsStaging.secondLevelCode = null
      form.itemsStaging.threeLevelCode = null
      form.itemsStaging.fourthLevelCode = null
      form.itemsStaging.fifthLevelCode = null
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition1)
      break
    }
    case 2: {
      form.itemsStaging.threeLevelCode = null
      form.itemsStaging.fourthLevelCode = null
      form.itemsStaging.fifthLevelCode = null
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition2)
      break
    }
    case 3: {
      form.itemsStaging.fourthLevelCode = null
      form.itemsStaging.fifthLevelCode = null
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition3)
      break
    }
    case 4: {
      form.itemsStaging.fifthLevelCode = null
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition4)
      break
    }
    case 5: {
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition5)
      break
    }
  }
}
const windowWidth = ref(1024)
// 附件
const handleUploadList = (v: any) => {
  form.fileIds = v.map((e: any) => e.file?.remoteId).join(',')
  fileImgList.value = v
}
const formInst = ref<FormInst | null>(null)
const submit = async () => {
  const pass = await submitR()
  if (!pass) return
  const validate = await Promise.all([
    // 暂时未使用
    // new Promise((resolve, reject) => {
    //   formInst.value?.validate((error) => {
    //     if (error) return reject(error)
    //     resolve(true)
    //   })
    // }),

    new Promise((resolve, reject) => {
      userFormRef.value?.validate((error) => {
        if (error) return reject(error)
        resolve(true)
      })
    })
  ])

  // if (!validate.every(Boolean)) return

  // if (!formInst.value) return
  // await formInst.value?.validate()

  if (!userFormRef.value) return
  await userFormRef.value.validate()
  loading.value = true
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'editEchoBySubItemCode',
    override: {
      data: {
        // id: form.id,
        fileIds: form.fileIds,
        itemsStaging: { ...form.itemsStaging, id: form.id },
        catalogInfo: {
          contentJson: JSON.stringify(formData.value || {}),
          id: form.id,
          subItemCode: form.subItemCode
        },
        subItemCode: form.subItemCode
      }
    }
  })
  loading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  window.flags.flushManageProcessTable = true
  routeReplace()
}
// 返回
const goBack = () => {
  // history.back()
  routeReplace()
}
const spinShow = ref(false)
const itemTypeCode = ref(null)
const findDetail = async () => {
  spinShow.value = true
  sendRequest({
    module: 'collectProcess',
    api: 'collectingItemsInfo',
    uri: {
      id: route.query.id
    }
  }).then(async ([err, res]) => {
    if (err) return
    spinShow.value = false
    await getFirstFn(0, optionInPosition0)
    await getFirstFn(res.data?.firstLevelCode, optionInPosition1)
    await getFirstFn(res.data?.secondLevelCode, optionInPosition2)
    await getFirstFn(res.data?.threeLevelCode, optionInPosition3)
    await getFirstFn(res.data?.fourthLevelCode, optionInPosition4)
    await getFirstFn(res.data?.fifthLevelCode, optionInPosition5)

    keysOf(res.data).forEach((e) => {
      form[e] = res.data[e] as never
    })
    itemTypeCode.value = res.data?.itemTypeCode
    await getInfo(res.data?.subItemCode, res.data?.itemCode)
    await getTimeLine(res.data?.subItemCode)
    form.itemsStaging.subItemCode = res.data?.subItemCode || null
    form.itemsStaging.firstLevelCode = res.data?.firstLevelCode
    form.itemsStaging.secondLevelCode = res.data?.secondLevelCode
    form.itemsStaging.threeLevelCode = res.data?.threeLevelCode
    form.itemsStaging.fourthLevelCode = res.data?.fourthLevelCode
    form.itemsStaging.fifthLevelCode = res.data?.fifthLevelCode
    form.itemsStaging.sixthLevelCode = res.data?.sixthLevelCode
  })
}

const getInfo = async (subItemCode: any, code: any) => {
  sendRequest({
    module: 'collectProcess',
    api: 'catalogInfoByCode',
    uri: {
      subItemCode: subItemCode
    }
  }).then(async ([err, res]) => {
    if (err) return
    form.fileIds = res.data?.collectingItems?.fileIds
    res.data?.collectingItems?.fileList?.map((i: any) => {
      fileImgList.value.push({
        name: i.name,
        url: i.path,
        path: i.path,
        status: 'finished',
        id: i.id
      })
    })
    formData.value = JSON.parse(
      res.data?.catalogInfo || `{"${defaultVersionTypeKey}": "${defaultVersionTypeValue}" }`
    )
    if (formData.value['BMCOM006'])
      formData.value['BMCOM006'] = formData.value['BMCOM006'].split('>').pop()
    checkIsDetail(code) //编辑-空值赋值
  })
}
const checkIsDetail = async (code: any) => {
  try {
    const [error, res] = await sendRequest({
      module: 'collectProcess',
      api: 'info',
      uri: {
        itemCode: code as string
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    const { data } = res
    form.fileIds = res.data?.fileIds
    res.data?.fileList?.map((i: any) => {
      fileImgList.value.push({
        name: i.name,
        url: i.path,
        path: i.path,
        status: 'finished',
        id: i.id,
        file: {
          remoteId: i.id
        }
      })
    })
    data.itemTypeCode && getCodeFn(data.itemTypeCode, data.itemName)
  } catch (error) {
    // console.error(error)
  } finally {
  }
}
// 获取对应的正题名字段
const getCodeFn = (e: any, target: any) => {
  // formData.value['BMCOM007'] = target
}
const timeLineData = ref() //流程数据
const getTimeLine = (code: any) => {
  return sendRequest({
    module: 'collectProcess',
    api: 'moveInfoTimeLine',
    uri: {
      subItemCode: code
    }
  }).then(async ([err, res]) => {
    if (err) return
    timeLineData.value = res.data
  })
}
watch(
  () => route,
  async () => {
    if (route.query.id) {
      if (route.name == 'edit_ManageProcess' || route.name == 'detail_ManageProcess') {
        fileImgList.value = []
        await findDetail()
      }
    }
  },
  { deep: true, immediate: true }
)
watch(()=>formData.value.ZRZ?.[0]?.['BMLSWX011'],(v)=>{
  formData.value['BMCOM008']= `${formData.value.ZRZ?.[0]?.['BMLSWX012'] || ''}${formData.value.ZRZ?.[0]?.['BMLSWX011'] ? '(' + formData.value.ZRZ?.[0]?.['BMLSWX011'] + ')' : ''}${formData.value.ZRZ?.[0]?.['BMLSWX013'] || ''}`
})
watch(()=>formData.value.ZRZ?.[0]?.['BMLSWX012'],(v)=>{
  formData.value['BMCOM008']= `${formData.value.ZRZ?.[0]?.['BMLSWX012'] || ''}${formData.value.ZRZ?.[0]?.['BMLSWX011'] ? '(' + formData.value.ZRZ?.[0]?.['BMLSWX011'] + ')' : ''}${formData.value.ZRZ?.[0]?.['BMLSWX013'] || ''}`
})
watch(()=>formData.value.ZRZ?.[0]?.['BMLSWX013'],(v)=>{
  formData.value['BMCOM008']= `${formData.value.ZRZ?.[0]?.['BMLSWX012'] || ''}${formData.value.ZRZ?.[0]?.['BMLSWX011'] ? '(' + formData.value.ZRZ?.[0]?.['BMLSWX011'] + ')' : ''}${formData.value.ZRZ?.[0]?.['BMLSWX013'] || ''}`
})
</script>

<template>
  <DetailFormProvider>
    <div
      class="main"
      id="main"
    >
      <div class="form_content">
        <NScrollbar>
          <NSpin :show="spinShow">
            <div style='display:flex'>
            <!-- <BatchInfo v-if="route.query?.type === '1'"/>  -->
            <div class="content">
              <div>
              <div class="dynamic-form-demo">
                <BatchInfo
                  v-if="route.query?.type === '1'"
                  style="margin-bottom: 10px"
                />
                <div class="bi-title">编目信息</div>
                <DynamicFormComponent
                  ref="dfInst"
                  :data="formData"
                  v-if="formData.BMCOM003"
                  :disabled="route.query?.type == 1"
                  :createVars="createVars"
                />
              </div>
              <div
                class="topTitle"
                v-show="fileImgList?.length > 0"
              >
                附件
              </div>
              <div
                class="detailinlineStyle"
                style="margin-top: 10px"
              >
                <n-form
                  :modal="form"
                  style="margin-left: 45px"
                >
                  <NFormItem
                    label="附件:"
                    path="fileIds"
                  >
                    <FUploader
                      v-if="route.query?.type == 0"
                      :file-list="fileImgList"
                      @update:fileList="handleUploadList"
                      style="width: 250px"
                    />
                    <VAttachments
                      v-else
                      :attach-list="fileImgList"
                    />
                  </NFormItem>
                </n-form>
                <!-- <span v-show='fileImgList?.length > 0' style='margin-right:10px'>附件:</span>
              <div>
                <n-image-group>
                  <n-space>
                    <n-image width="100" height="100" :src="i.url" :key="i.id" v-for="i in fileImgList" />
                  </n-space>
                </n-image-group>
              </div> -->
              </div>
              <div
                class="topTitle"
                v-if="route.query?.type == 0"
              >
                入库
              </div>
              <NForm
                :model="form"
                :rules="formRules"
                ref="userFormRef"
                label-placement="left"
                label-width="140rem"
                require-mark-placement="left"
                v-if="route.query?.type == 0"
              >
                <NSpace>
                  <NFormItem
                    label="入库位置:"
                    path="itemsStaging.firstLevelCode"
                  >
                    <NSelect
                      v-model:value="form.itemsStaging.firstLevelCode"
                      placeholder="位置1"
                      class="inputWHmin"
                      filterable
                      clearable
                      :options="optionInPosition0"
                      @update-value="(e) => changeOptionFn(e, 1)"
                      :render-option="renderOption1"
                      :disabled="route.query?.type == 1"
                    />
                  </NFormItem>
                  <NFormItem
                    label=""
                    path="itemsStaging.secondLevelCode"
                  >
                    <NSelect
                      v-model:value="form.itemsStaging.secondLevelCode"
                      placeholder="位置2"
                      class="inputWHmin"
                      filterable
                      clearable
                      :options="optionInPosition1"
                      @update-value="(e) => changeOptionFn(e, 2)"
                      :render-option="renderOption1"
                      :disabled="route.query?.type == 1"
                    />
                  </NFormItem>
                  <NFormItem
                    label=""
                    path="itemsStaging.threeLevelCode"
                  >
                    <NSelect
                      v-model:value="form.itemsStaging.threeLevelCode"
                      placeholder="位置3"
                      class="inputWHmin"
                      filterable
                      clearable
                      :options="optionInPosition2"
                      @update-value="(e) => changeOptionFn(e, 3)"
                      :render-option="renderOption1"
                      :disabled="route.query?.type == 1"
                    />
                  </NFormItem>
                  <NFormItem
                    label=""
                    path="itemsStaging.fourthLevelCode"
                  >
                    <NSelect
                      v-model:value="form.itemsStaging.fourthLevelCode"
                      placeholder="位置4"
                      class="inputWHmin"
                      filterable
                      clearable
                      :options="optionInPosition3"
                      @update-value="(e) => changeOptionFn(e, 4)"
                      :render-option="renderOption1"
                      :disabled="route.query?.type == 1"
                    />
                  </NFormItem>
                  <NFormItem
                    label=""
                    path="itemsStaging.fifthLevelCode"
                  >
                    <NSelect
                      v-model:value="form.itemsStaging.fifthLevelCode"
                      placeholder="位置5"
                      class="inputWHmin"
                      filterable
                      clearable
                      :options="optionInPosition4"
                      @update-value="(e) => changeOptionFn(e, 5)"
                      :render-option="renderOption1"
                      :disabled="route.query?.type == 1"
                    />
                  </NFormItem>
                  <NFormItem
                    label=""
                    path="itemsStaging.sixthLevelCode"
                  >
                    <NSelect
                      v-model:value="form.itemsStaging.sixthLevelCode"
                      placeholder="位置6"
                      class="inputWHmin"
                      filterable
                      clearable
                      :options="optionInPosition4"
                      @update-value="(e) => changeOptionFn(e, 6)"
                      :render-option="renderOption1"
                      :disabled="route.query?.type == 1"
                    />
                  </NFormItem>
                </NSpace>
              </NForm>
            </div>
            </div>
            <div class="content1">
                <div class="topTitle">生命周期</div>
                <div class="item">
                  <n-timeline
                    class="itemSon"
                    style="margin-left: 50rem; margin-top: 30rem; margin-right: 150rem"
                  >
                    <n-timeline-item
                      v-for="i in timeLineData"
                      type="success"
                      line-type="default"
                    >
                      <span class="namePosition">{{ i.processName }}</span>
                      <div
                        style="height: 20px"
                        v-for="m in i.moveItemList"
                      >
                        {{ m.keyName }}:
                        <NEllipsis style="max-width: 140px">{{ m.valueName }}</NEllipsis>
                      </div>
                    </n-timeline-item>
                  </n-timeline>
                  <!-- <n-timeline
                    class="itemSon"
                    style="margin-left: 150rem; margin-top: 30rem; margin-right: 150rem"
                    horizontal
                  >
                    <n-timeline-item
                      v-for="i in timeLineData"
                      type="success"
                      line-type="default"
                    >
                      <span class="namePosition">{{ i.processName }}</span>
                      <div
                        style="height: 20px"
                        v-for="m in i.moveItemList"
                      >
                        {{ m.keyName }}:
                        <NEllipsis style="max-width: 140px">{{ m.valueName }}</NEllipsis>
                      </div>
                    </n-timeline-item>
                  </n-timeline> -->
                </div>
              </div>
            </div>
          </NSpin>
        </NScrollbar>
      </div>
      
    </div>
  </DetailFormProvider>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        {{ route.query?.type == 0 ? '取消' : '返回' }}
      </NButton>
      <NButton
        type="primary"
        style="width: 78px"
        @click="submit"
        :loading="loading"
        v-if="route.query?.type == 0"
      >
        保存
      </NButton>
    </NSpace>
  </FixedAction>
</template>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;
  .dynamic-form-demo {
    background-color: #e1e1e1;
    padding: 30px 45px 10px;
    // height:300px;
  }
  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;
    .bi-title {
      font-size: 26rem;
      margin-bottom: 30rem;
      color: #048c5e;
      line-height: 1;
    }
    .topTitle {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }

    .inputWH {
      flex: 1;
    }

    .inputWHmin {
      width: 150rem;
    }

    .content {
      display: flex;
      flex-direction: column;
      width: 80%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      @include CommonFont;
    }
  
  }
  .content1 {
      width: 20%;
      height: 100%;
      // margin-left: 10rem;
      margin-bottom: 100rem;;
      background-color: #ebeceb;
      @include CommonFont;
      .item {
        :deep(.n-timeline-item-timeline__circle) {
          background-color: #008000;
          border: 1px solid #008000;
        }
        .itemSon {
          :deep(
              .n-timeline
                .n-timeline-item
                .n-timeline-item-content
                .n-timeline-item-content__content
            ) {
            transform: translate(-50%, 0);
            // margin-top: 144px;
          }
          .namePosition {
            width: 100%;
            text-align: center;
            text-align: center;
            position: absolute;
            top: 0;
            left: -50%;
            transform:translate(-30rem,0)
          }
        }
        // .itemSon:nth-child(even) {
        //   :deep(.n-timeline .n-timeline--horizontal){
        //   flex-direction: row-reverse !important;
        //  }
        // }
      }
    }
  // .namePosition {
  //   top: 2rem;
  //   // left: 55%;
  //   z-index: 112;
  //   .stepItemInner_content {
  //     position: relative;
  //     width: 100%;
  //     width: 100%;
  //     text-align: center;
  //     text-align: center;
  //     position: absolute;
  //     top: -60rem;
  //     left: 7rem;
  //   }
  // }
}
.stepOut {
  width: 100%;
  margin-top: 32rem;
  margin-left: 150rem;
  ul {
    width: 1440rem;
    li {
      list-style: none;
    }
  }
  .stepItem {
    width: 240rem;
    height: 150rem;
    float: left;
    font-size: 14rem;
    text-align: center;
    position: relative;
    .stepItemInner {
      position: absolute;
      width: 100%;
      height: 100%;
      top: 2rem;
      // left: 55%;
      z-index: 112;
      .stepItemInner_content {
        position: relative;
        width: 100%;
        height: 100%;
        .step_bg {
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;
          width: 12rem;
          height: 12rem;
          border-radius: 50%;
          background-color: #008000;
        }
        .stepTime {
          position: absolute;
          top: -27rem;
          left: 6rem;
          transform: translateX(-50%);
          font-size: 14rem;
          text-align: center;
          color: #232527;
        }
        .stepStatus {
          position: absolute;
          top: 26rem;
          left: 12rem;
          font-size: 14rem;
          color: #ff9900;
        }
        .statusDesc {
          position: absolute;
          top: 19rem;
          left: -50%;
          font-size: 14rem;
          color: #232527;
          width: 100%;
          transform: translateX(6rem);
        }
      }
    }
    .lineCircle {
      left: 0;
      top: 6rem;
      position: absolute;
      display: block;
      border-left-color: white;
      border-left-width: 0rem;
      width: 160rem;
      border-color: white white white white;
      border-left-style: hidden;
      border-left: none;
      border-top: 2rem solid #dbdbdf;
      border-right: 2rem solid #dbdbdf;
      border-bottom: 2rem solid #dbdbdf;
      border-bottom: 2rem solid #dbdbdf;
      border-left: 0rem solid #c0c4cc;
      height: 152rem;
      border-radius: 0rem 80rem 80rem 0rem;
    }
    &:nth-child(n + 6) {
      float: right !important;
      right: 0;
    }
    &.stepItemLeftStart {
      float: left !important;
      right: 0;
      + .stepItemBrother {
        .line {
          display: none;
        }
      }
    }
    .lineCircleLeft {
      left: -50%;
      width: 120rem;
      box-sizing: border-box;
      border-top: 2rem solid #dbdbdf;
      border-right: 0 solid #c0c4cc;
      border-bottom: 2rem solid #dbdbdf;
      border-bottom: 2rem solid #dbdbdf;
      border-left: 2rem solid #dbdbdf;
      border-radius: 80rem 0rem 0rem 80rem;
      height: 152rem;
    }
    .line {
      position: absolute;
      top: 6rem;
      // left: 74.5%;
      left: 0;
      border-bottom: 2rem solid #dbdbdf;
      width: 240rem;
      z-index: 111;
    }
  }
}
.detailinlineStyle {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
  margin-left: 20px;
}
.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
